package it.uai.domainsMigrator;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.log4j.Logger;

public class ExecuteDatabaseBackup {

	private static final Logger logger = Logger
			.getLogger(ExecuteDatabaseBackup.class);
	String command;
	String fileName;
	String backupFileName;

	public ExecuteDatabaseBackup(String DBName, String DBUsername,
			String destinationPath, String fileName) throws IOException, InterruptedException {

		this.fileName = fileName;

		if (!destinationPath.endsWith("/")) {
			destinationPath.substring(0, destinationPath.length() - 1);
		}

		makeBackupDir(destinationPath);

		backupFileName = destinationPath + "/" + fileName;

		// mysqldump stellevariabili > /backup_mysql/stellevariabili.sql -u
		// uaibackup
		command = "mysqldump -B " + DBName + " -u " + DBUsername + " -r " + backupFileName ;

		logger.debug("COMANDO BACKUP: " + command);
		
		System.out.println("COMANDO BACKUP: " + command);

		Process p = Runtime.getRuntime().exec(command);
		
		p.waitFor();
		
		compressDump();

	}

	public void makeBackupDir(String path) {

		File directory = new File(path);
		directory.mkdirs();
		logger.trace("Creata directory:" + directory.getAbsolutePath());

	}

	public void compressDump() throws IOException {

		FileInputStream in = new FileInputStream(backupFileName);
		// out put file

		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
				backupFileName + ".zip"));
		// name the file inside the zip file

		out.putNextEntry(new ZipEntry(fileName));

		byte[] b = new byte[1024];

		int count;

		while ((count = in.read(b)) > 0) {
			System.out.println();

			out.write(b, 0, count);
		}
		out.close();
		in.close();

	}

}
